package com.yhao.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
	
	public static byte[] getMD5Byte(final String data) {
		return getMD5Byte(data.getBytes());
	}
	public static byte[] getMD5Byte(final byte[] data) {
		try {
			final MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(data);
			return digest.digest();
		} catch (final Exception e) {
		}
		return null;
	}
	
	public static String getMd5String(String sSecret) {
		try {
			MessageDigest bmd5 = MessageDigest.getInstance("MD5");
			bmd5.update(sSecret.getBytes());
			int i;
			StringBuffer buf = new StringBuffer();
			byte[] b = bmd5.digest();
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
		}
		return "";
		
	}
	
//	private static String checkMd5(File f) {
//
//        FileInputStream fis = null;
//        byte[] rb = null;
//        DigestInputStream digestInputStream  = null;
//        try {
//            fis = new FileInputStream(f);
//            MessageDigest md5 = MessageDigest.getInstance("md5");
//            digestInputStream = new DigestInputStream(fis,
//                    md5);
//            byte[] buffer = new byte[4096];
//            while (digestInputStream.read(buffer) > 0)
//                ;
//            md5 = digestInputStream.getMessageDigest();
//            rb = md5.digest();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally{
//            try {
//                fis.close();
//            } catch (IOException e) {
//            }
//        }
//
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < rb.length; i++) {
//            String a = Integer.toHexString(0XFF & rb[i]);
//            if (a.length() < 2) {
//                a = '0' + a;
//            }
//            sb.append(a);
//        }
//        return sb.toString();
//    }
}
